package com.webflux.service;

import com.webflux.entity.ElasticSearchEntity;
import com.webflux.entity.UserEntity;
import com.webflux.model.UserDO;
import com.webflux.repository.UserElasticSearchRepository;
import com.webflux.repository.UserRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class UserService {

    @Autowired
    private UserRepository userRepository;
    @Autowired
    private ElasticSearchService elasticSearchService;
    @Autowired
    private UserElasticSearchRepository userElasticSearchRepository;


    public Mono<UserDO> save(UserDO userDO) throws IOException {

        userDO.setCreateTime(new Date().getTime());
        elasticSearchService.createDocument("t_user", new ElasticSearchEntity(userDO));
        return userRepository.save(userDO);

    }


    public Mono<UserDO> findById(Integer id) {
        Mono<UserDO> mono = userRepository.findById(id);
        return mono;
    }


    public Flux<UserDO> findAll() throws IOException {
        Flux<UserDO> userDOFlux = userRepository.findAll();

        List<UserDO> list = userDOFlux.collectList().block();


        List<UserEntity> userEntityList = new ArrayList<>();
        List<ElasticSearchEntity> elasticSearchEntities = new ArrayList<>();
        if (list != null && list.size() > 0) {

            for (UserDO item : list) {

                UserEntity userEntity = new UserEntity(item);

                userEntityList.add(userEntity);
                elasticSearchEntities.add(new ElasticSearchEntity(userEntity));
            }

        }
//        elasticSearchService.batchCreate("t_user", elasticSearchEntities);
        elasticSearchService.batchCreate(userEntityList);
        return userDOFlux;
    }


}
